package org.onvivals.app.ai.asr;

import com.alibaba.nls.client.AccessToken;
import com.alibaba.nls.client.protocol.NlsClient;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
public class NlsClientService {

	private static NlsClient client;

	private static AccessToken accessToken;

	public NlsClientService(String accessKeyId, String accessKeySecret, String url) {

		//创建NlsClient实例,应用全局创建一个即可,生命周期可和整个应用保持一致,默认服务地址为阿里云线上服务地址
		applyAccessToken(accessKeyId, accessKeySecret);
		if (url.isEmpty()) {
			client = new NlsClient(accessToken.getToken());
		} else {
			client = new NlsClient(url, accessToken.getToken());
		}
	}

	public static AccessToken getAccessToken() {
		return accessToken;
	}

	public static void applyAccessToken(String accessKeyId, String accessKeySecret) {
		accessToken = new AccessToken(accessKeyId, accessKeySecret);
		try {
			accessToken.apply();
			log.info("get token: " + accessToken.getToken() + ", expire time: " + accessToken.getExpireTime());
		} catch (IOException e) {
			log.error("https获取accessToken失败！" + e.getMessage());
		}
	}

	public static NlsClient getNlsClient() {
		return client;
	}
}
